const connection = require("../app/database");

class OrderService {
  // 添加用户订单
  async insertUserOrder(
    orderNumber,
    userId,
    listId,
    totalPrice,
    startDate,
    endDate,
    totalRestNight
  ) {
    const statement = `INSERT INTO user_order (order_number, user_id, list_id, total_price, start_date, end_date, total_rest_night) VALUES(?, ?, ?, ?, ?, ?, ?);`;
    const [res, fields] = await connection.execute(statement, [
      orderNumber,
      userId,
      listId,
      totalPrice,
      startDate,
      endDate,
      totalRestNight,
    ]);
    return res;
  }
  // 支付完成修改用户订单状态
  async updateStatusToPaid(orderNumber) {
    const statement = `UPDATE user_order SET status = 'paid' WHERE order_number = ?;`;
    await connection.execute(statement, [orderNumber]);
  }
  // 根据用户id获取所有订单
  async getOrdersByUserId(userId) {
    const statement = `SELECT 
                        id, 
                        order_number AS orderNumber, 
                        user_id AS userId, 
                        list_id AS listId, 
                        total_price AS totalPrice, 
                        start_date AS startDate,
                        end_date AS endDate,
                        total_rest_night AS totalRestNight,
                        status
                        FROM user_order WHERE user_id = ?;`;
    const [res, fields] = await connection.execute(statement, [userId]);
    return res;
  }
  // 根据时间修改用户订单状态
  async updateStatusByTime(status, id) {
    const statement = `UPDATE user_order SET status = ? WHERE id = ?;`;
    await connection.execute(statement, [status, id]);
  }
  // 根据订单号取消行程
  async deleteOrderByNumber(orderNumber) {
    const statement = `DELETE FROM user_order WHERE order_number = ?;`
    await connection.execute(statement, [orderNumber])
  }
}

module.exports = new OrderService();
